package org.huntaway.kernel.imp;

import java.io.IOException;
import java.security.CodeSource;
import java.util.jar.JarFile;

import org.huntaway.kernel.CurrTools;
import org.huntaway.kernel.NutException;
import org.huntaway.kernel.imp.base.BaseCurrTools;

public class CurrToolsImp extends BaseCurrTools {
	public static String DEFAULT_CHATSET = "GBK";

	/**
	 * @param classStr
	 * @param enc
	 * @return
	 * @throws
	 */
	private String getClassDir(Class clazz, String enc) {
		CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();
		if (codeSource == null) {
			throw new NutException(new NullPointerException(clazz
					+ " dir is missing..."));
		} else {
			return decode(codeSource.getLocation().getFile());
		}

	}

	public String getCurrDir() {
		return decode(this.getClass().getClassLoader().getResource("")
				.getPath());

	}

	/**
	 * @param str
	 * @return
	 */
	public String iso2Gbk(String str) {
		return transCode(str, "iso8859-1", "GBK");

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.huntaway.kernel.CurrTools#getClassDir(java.lang.Class)
	 */
	public String getClassDir(Class clazz) {
		return getClassDir(clazz, Default_charSet);
	}

	public String getJarDir(Class clazz) {
		return getClassDir(clazz);
	}

	public JarFile getJarFile(Class clazz) {
		JarFile jarFile;
		try {
			jarFile = new JarFile(getClassDir(clazz, Default_charSet));
		} catch (IOException e) {
			throw new NutException(e);
		}
		return jarFile;
	}

	/**
	 * @param str1
	 * @param str2
	 * @return
	 */
	public double sim(String str1, String str2) {
		int ld = ld(str1, str2);
		return 1 - (double) ld / Math.max(str1.length(), str2.length());
	}

	/**
	 * @param str1
	 * @param str2
	 * @return
	 */
	public double sim1(String str1, String str2) {
		int ld = ld(str1, str2);
		return Math.abs(1 - (double) ld)
				/ Math.max(str1.length(), str2.length());
	}

	/**
	 * @param str1
	 * @param str2
	 * @return
	 */
	public double sim2(String str1, String str2) {
		double ld = ld(str1, str2);
		return 1 / (ld + 1);
	}

	/**
	 * @param str
	 * @return
	 */
	public String utf82Gbk(String str) {
		return transCode(str, "utf-8", "GBK");

	}

	/**
	 * @param str
	 * @return
	 */
	public String utf162Gbk(String str) {
		return transCode(str, "utf-16", "GBK");

	}

	public String getResourcePath() {
		String strPath = CurrTools.class.getClassLoader().getResource("")
				.getPath();
		return strPath.substring(1);

	}
}
